package com.example.demo.controller;

import com.example.demo.dao.UsersDao;
import com.example.demo.model.UsersEntity;
import com.example.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
public class UsesController {
    @Autowired
    UsersDao usersDao;

    @GetMapping("/api/username")
    public String getByUsername(String username) {
        return Result.success(usersDao.findByUsername(username));
    }

    @GetMapping("/api/user")
    public String select(int id) {
        Optional<UsersEntity> optional = usersDao.findById(id);
        if (optional.isPresent()) {
            return Result.success(optional.get());
        }
        return Result.error();
    }

    @PostMapping("/api/user")
    public String create(UsersEntity user) {
        usersDao.save(user);
        return Result.success(user);
    }

    @PutMapping("/api/user")
    public String updateUsername(int id, String username) {
        Optional<UsersEntity> optional = usersDao.findById(id);
        if (optional.isPresent()) {
            UsersEntity usersEntity = optional.get();
            usersEntity.setUsername(username);
            usersDao.save(usersEntity);
        }
        return "success message:修改成功";
    }

//    @PostMapping("/api/user")
//    public void updatePassword(int id, String password) {
//        Optional<UsersEntity> optional = dao.findById(id);
//        if (optional.isPresent()) {
//            UsersEntity usersEntity = optional.get();
//            usersEntity.setPassword(password);
//            dao.save(usersEntity);
//        }
//    }

    @DeleteMapping("/api/user")
    public String delete(UsersEntity user) {
        usersDao.delete(user);
        if (usersDao.findById(user.getId()).isPresent()) {
            return Result.error();
        } else {
            return Result.success();
        }
    }
}
